package com.mcr.graduateprogram.filter;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mcr.graduateprogram.bean.GameSpecification;
import com.mcr.graduateprogram.bean.Gamekeys;
import com.mcr.graduateprogram.bean.KeysExcel;
import com.mcr.graduateprogram.service.IGameSpecificationService;
import com.mcr.graduateprogram.service.IGamekeysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Configuration
public class ExcelListener extends AnalysisEventListener<KeysExcel> {
    @Autowired
    private IGameSpecificationService gameSpecificationService;
    @Autowired
    private IGamekeysService gamekeysService;
    private Integer sum=0;
    private List<Gamekeys> keysList=new ArrayList<>();
    private Long specificationId=0L;
    private HashMap<String,Boolean> map=new HashMap<>();
    @Override
    public void invoke(KeysExcel keysExcel, AnalysisContext analysisContext) {
        if(analysisContext.readRowHolder().getRowIndex()==1){
            specificationId=keysExcel.getSpecificationId();
        }else if(analysisContext.readRowHolder().getRowIndex()==2){
            sum= Math.toIntExact(keysExcel.getSpecificationId());
        }
        Gamekeys keys=new Gamekeys();
        keys.setGamekey(keysExcel.getKey());
        keys.setSpecificationId(specificationId);
        if(map.get(keys.getGamekey())==null){//同一批相同的激活码将只能导入一个
            keysList.add(keys);
            map.put(keys.getGamekey(),true);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        gamekeysService.saveBatch(keysList);
        LambdaUpdateWrapper<GameSpecification> gameSpecificationLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        gameSpecificationLambdaUpdateWrapper.eq(GameSpecification::getId,specificationId)
                .set(GameSpecification::getNumber,sum+keysList.size());
        gameSpecificationService.update(gameSpecificationLambdaUpdateWrapper);
        sum=0;
        keysList=new ArrayList<>();
        specificationId=0L;
        map=new HashMap<>();
    }
}
